package com.java.tutorials.threads.atomic;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by xuzhike on 2016/1/20.
 * http://www.java2s.com/Code/Java/Threads/AtomicUtils.htm
 */
public final class AtomicUtils {

    private AtomicUtils() {}

    public static boolean tryIncrementIfLessThan(final AtomicInteger capacity, final int atmost) {
        int capa;
        do {
            capa = capacity.get();
            if(capa >= atmost) {
                return false;
            }
        } while(!capacity.compareAndSet(capa, capa + 1));
        return true;
    }

    public static int tryIncrementAndGetIfLessThan(final AtomicInteger capacity, final int upperbound) {
        for(;;) {
            final int current = capacity.get();
            if(current >= upperbound) {
                return upperbound;
            }
            final int next = current + 1;
            if(capacity.compareAndSet(current, next)) {
                return next;
            }
        }
    }

    public static boolean tryIncrementIfGreaterThan(final AtomicInteger capacity, final int least) {
        int capa;
        do {
            capa = capacity.get();
            if(capa <= least) {
                return false;
            }
        } while(!capacity.compareAndSet(capa, capa + 1));
        return true;
    }

    public static boolean tryDecrementIfGreaterThan(final AtomicInteger capacity, final int least) {
        int capa;
        do {
            capa = capacity.get();
            if(capa <= least) {
                return false;
            }
        } while(!capacity.compareAndSet(capa, capa - 1));
        return true;
    }

    public static int tryDecrementAndGetIfGreaterThan(final AtomicInteger capacity, final int least) {
        for(;;) {
            final int current = capacity.get();
            if(current <= least) {
                return current;
            }
            final int next = current - 1;
            if(capacity.compareAndSet(current, next)) {
                return next;
            }
        }
    }

}
